package main

import (
	pb "03-grpc-stream/proto"
	"context"
	"fmt"
	"sync"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func main() {
	conn, err := grpc.NewClient("0.0.0.0:3001", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	// getStream
	c := pb.NewStreamClient(conn)
	res, _ := c.GetStream(context.Background(), &pb.ReqMessage{Data: "请发送数据"})
	for {
		a, err := res.Recv()
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(a.Data)
	}

	//putStream
	putS, _ := c.PutStream(context.Background())
	i := 0
	for {
		i++
		_ = putS.Send(&pb.ReqMessage{
			Data: fmt.Sprintf("数据%d", i),
		})
		time.Sleep(time.Second)
		if i > 5 {
			break
		}
	}

	//allStream
	allStr, _ := c.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := allStr.Recv()
			fmt.Println("收到服务器数据:", data.Data)
		}
	}()

	go func() {
		defer wg.Done()
		for {
			_ = allStr.Send(&pb.ReqMessage{Data: "Mooc"})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()
}
